import * as shell from 'shelljs'
import logger, { simpleLogger } from '@main/utils/logger'

const ERROR_KEY_TEXT = "BUILD FAILURE"
const SUCCESS_KEY_TEXT = "BUILD SUCCESS"

const isErrorLog = log => {
  return log.indexOf(ERROR_KEY_TEXT) >= 0
}

const isSuccessLog = log => {
  return log.indexOf(SUCCESS_KEY_TEXT) >= 0
}

const logBoundary = (key) => {
  return logger.info(`>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ${key} >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>`)
}

/**
 * 执行异步命令, 时时回调日志
 * @param {string} cmd 
 * @param {(log:string) => void} logCallback 
 * @returns 
 */
export const exceWithLogCallback = (cmd, logCallback) => {
  return new Promise((resolve, reject) => {
    let isSuccess = null;
    let logText = "";
    logBoundary("Start")
    logger.info('执行命令: ' + cmd)
    const child = shell.exec(cmd, { async: true, silent: true })
    child.stdout?.on('data', (log) => {
      if (log && !new RegExp('^\\s*$').test(log)) {
        simpleLogger.info(log.replace(new RegExp('(\\r\\n)$', 'g'), ''))
        logCallback(log)
        logText += log;
      }
      if(isSuccessLog(log)){
        isSuccess = true
      }
      if(isErrorLog(log)){
        isSuccess = false;
      }
    })
    child.stderr?.on('data', (data) => {
      simpleLogger.error(data)
    })
    child.on('exit', (code, signal) => {
      logCallback('\n');
      logBoundary("End")
      resolve({
        isSuccess,
        logText: isSuccess ? '' : logText
      })
    })
  })
}

/**
 * 执行命令， 返回同步日志
 * @param {string} cmd 
 */
export const exce = (cmd) => {
  const start = Date.now();
  return new Promise((resolve, reject) => {
    logBoundary("Start")
    logger.info('执行命令: ' + cmd)
    shell.exec(cmd, { async: true, silent: true }, (code, stdout, stderr) => {
      logBoundary("Etart")
      const isSuccess = code === 0;
      resolve({
        isSuccess,
        logText: isSuccess ? stdout : (stderr || stdout),
        duration: Date.now() - start
      })
    })
  })
}
